#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2019-01-31 11:13:30
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.6.5
# 功能     ：

import os, time_ext_, sys, re, win32api
import tools


def get_argv():
    if len(sys.argv) > 1:
        argv = [v.lower() for v in sys.argv]
        return argv
    else:
        return False


# 打包成exe
def toExe(file, v = '', icon = None, gui = None, oneFile = None, name = None):
    try:
        filePath = os.path.abspath(file)
        icon = '-i=' + os.path.abspath(icon) if icon else ""
        gui = ' -w ' if gui else ""
        oneFile = ' -F ' if oneFile else ' -D '
        dirPath, fileName = os.path.split(filePath)
        cmdName = "{}_ToExe.bat".format(os.path.splitext(fileName)[0])
        cmdPath = "{}/{}".format(dirPath, cmdName)
        name = '-n {}'.format(name) if name else ''
        with open(cmdPath, 'w') as f:
            cmd = """
                    @echo {fileName}:打包成EXE文件。。。。。。。。。。
                    CD {root}
                    CD {cd}
                    Pyinstaller{v}  {gui} {icon} {oneFile} -p E:\\app\\python373\\DLLs;E:\\app\\python373\\Lib\\site-packages;./ -y {fileName} {name}
                    pause
                    """.format(root = dirPath[:2], cd = dirPath, gui = gui, icon = icon, oneFile = oneFile,
                               fileName = fileName, v = v, name = name)

            f.write(cmd)
        print("PyInstaller打包：", file)
        win32api.ShellExecute(0, 'open', cmdPath, '', '', 1)
    except Exception as e:
        s = """
            file 需要打包的文件名称 (必须参数)
            icon 图标文件路径 (可选参数)
            gui  是否带UI  (可选参数 bool)
            oneFile 是否打包成一个文件 (可选参数 bool)
        """
        print(s)


def toExe2(file, icon = None, gui = None, outDir = None, dirFile = True):
    filePath = os.path.abspath(file)
    dirFile = '--standalone' if dirFile else ""
    icon = '--windows-icon=' + os.path.abspath(icon) if icon else ""
    gui = '--windows-disable-console' if gui else ""
    outDir = '--output-dir=' + os.path.abspath(outDir) if outDir and os.path.isdir(outDir) else ""
    dirPath, fileName = os.path.split(filePath)
    cmdName = "{}_nuitka_ToExe.bat".format(os.path.splitext(fileName)[0])
    cmdPath = "{}/{}".format(dirPath, cmdName)

    with open(cmdPath, 'w') as f:
        cmd = """
                @echo {fileName}:打包成EXE文件。。。。。。。。。。
                CD {root}
                CD {cd}
                nuitka {gui} {icon} {outDir} {dirFile} --follow-imports --recurse-all --remove-output {fileName}
                pause
                """.format(root = dirPath[:2], cd = dirPath, gui = gui, icon = icon, outDir = outDir,
                           fileName = fileName, dirFile = dirFile)

        f.write(cmd)
    print("nuitka打包:", file, cmdPath)
    win32api.ShellExecute(0, 'open', cmdPath, '', '', 1)


def toPyd(pyFile, out_dir = '.'):
    pyFile = os.path.abspath(pyFile)
    if re.findall('^\w:', pyFile):
        dirs = os.path.split(pyFile)
        cmdName = "{}_ToPyd.bat".format(dirs[1].split('.')[0])
        cmdPath = os.path.join(out_dir, cmdName)

        with open(cmdPath, 'w') as f:
            cmd = """
                @echo {}模块：{}打包成PYD文件{}
                CD {}
                CD {}
                python -m nuitka --recurse-all --output-dir={} --remove-output --module {}
                pause
                """.format('*' * 20, dirs[1], '*' * 20, dirs[0][:2], dirs[0], out_dir, dirs[1])
            f.write(cmd)
        win32api.ShellExecute(0, 'open', cmdPath, '', '', 1)
        # #命令
        # CMD='cd {} & cd {} & python -m nuitka  --output-dir={} --remove-output --module {}'.format(dirs[:2],dirs,out_dir,pyFile)
        # print("command=%s"%CMD)
        # win32api.ShellExecute(0,'cmd','ping 127.0.0.1','',1)
    else:
        pass


def toPyd_v2(pyx, out_dir = '.'):
    exp = os.path.splitext(pyx)[0]
    scr = """
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
    ext_modules=cythonize([

        Extension("{exp}", ["{exp}.pyx"]),

        ]),
    )
    """.format(exp = exp)
    with open('setup.py', 'w+', encoding = 'utf-8') as f:
        f.write(scr)
    bat = './' + exp + '.bat'
    cmd = "python setup.py build_ext --inplace"
    with open(bat, "w+") as f:
        f.write(cmd)
    win32api.ShellExecute(0, 'open', os.path.abspath(bat), '', '', 1)


def toPy(path = '.'):
    file = os.listdir(path)
    for v in file:
        exp = os.path.splitext(v)
        cmd = None
        new_file = None
        print(exp)
        if os.path.isfile(v) and exp[1] == '.ui':
            cmd = f"pyuic5 -o {exp[0]}.py {v}"
            new_file = os.path.abspath(exp[0] + '.py')
            print(" * QT设计师Ui文件转换成py,命令：{}\n".format(cmd))
        elif os.path.isfile(v) and exp[1] == '.qrc':
            cmd = f"pyrcc5 -o {exp[0]}_rc.py {v}"
            print(" * QT设计师Qrc资源文件转换成py,命令：{}\n".format(cmd))
            new_file = os.path.abspath(exp[0] + '.py')
        _ = os.system(cmd) if cmd else 0
        if new_file:
            print(" * 生成文件：{}\n".format(new_file))
            print('-' * 140)


# nuitka 打包exe
def nuitka_exe(file, icon = None, gui = None):
    # 打包脚本
    NUITKA = os.path.abspath(file)
    # 当前目录
    CWD = os.getcwd().replace("\\", "/")
    # MSVC路径
    MSVC = r"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvars32.bat"
    # MSVC命令
    command = '"{}" x86 &'.format(MSVC)
    # 打包命令
    command += "nuitka "

    command += "--output-dir={}/output ".format(CWD)
    # 优化显示
    command += "--verbose "
    # 显示scons在非安静模式下操作scons，显示执行
    command += "--show-scons "
    # GUI
    if gui:
        command += "--windows-disable-console "
    # icon
    if icon:
        absIcon = os.path.abspath(icon).replace("\\", '/')
        command += "--windows-icon={} ".format(absIcon)
    # 独立应用
    command += "--standalone "
    # 整合
    command += "{} ".format(NUITKA)
    print("执行的命令：{}".format(command))
    print("开始。。。。")
    os.system(command)


def nuitka_modues(file):
    # nuitka --module some_package --include-package = some_package
    # 打包脚本
    # NUITKA = os.path.abspath(file)
    # 当前目录
    CWD = os.getcwd().replace("\\", "/")
    # MSVC路径
    MSVC = r"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvars32.bat"
    # MSVC命令
    command = '"{}" x86 &'.format(MSVC)
    # 打包命令
    command += "nuitka "
    # 输出
    command += "--output-dir={}/output ".format(CWD)
    #
    command += "--module {} ".format(file)
    print("执行的命令：{}".format(command))
    print("开始。。。。")
    os.system(command)


if __name__ == '__main__':
    nuitka_modues('./de')
# if __name__ == '__main__':
#     argv=get_argv()
#     if argv and 'toExe' in argv :
#         icon=None
#         gui=None
#         oneFile=None
#         if 'icon='in argv:
#             i=[ for v in argv if re.findall('icon=')]
#             print('icon',argv)
#         if 'gui=' in argv:
#             pirnt('gui',argv)
#         if 'oneFile=' in argv:
#             print('oneFile',argv)
#         toExe(argv[-1],icon,gui,oneFile)